package com.haliyoo.adhere.handler;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.haliyoo.adhere.R;
import com.haliyoo.adhere.activity.CreativeActivity;
import com.haliyoo.adhere.activity.CreativeDesignActivity;
import com.haliyoo.adhere.activity.HallActivity;
import com.haliyoo.adhere.activity.LoginActivity;
import com.haliyoo.adhere.bean.WeiboBean;
import com.haliyoo.adhere.controller.AdUserConstant;
import com.haliyoo.adhere.controller.OAuthConstant;
import com.haliyoo.adhere.util.DateUtilsDef;
import com.haliyoo.adhere.widget.DialogListener;
import com.haliyoo.adhere.widget.PromptDialog;
import com.haliyoo.adhere.widget.WeiboLayout;

import weibo4android.Count;
import weibo4android.Paging;
import weibo4android.Status;
import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.AccessToken;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CreativeHallHandler {
	private static String TAG = "CreativeHallHandler";
	private WeiboList weiboList = null;
	private static User user = null;
	public static Weibo weibo = null;
	private static CreativeHallHandler instance = null;
    private static Context context = null;

	public static synchronized CreativeHallHandler getInstance(Context context) {
		if (HallActivity.getCheckedId() != R.id.radio_hall) {
			return null;
		}
		
		if(instance == null) {
			instance = new CreativeHallHandler(context);
		}
		
		return instance;
	}
    
    public CreativeHallHandler(Context context) {
		if (HallActivity.getCheckedId() != R.id.radio_hall) {
			return;
		}
		
    	this.context = context;

        LayoutInflater inflater = LayoutInflater.from(context);
        
		// / 设置标题栏
		RelativeLayout rlTitle = (RelativeLayout) ((Activity) context)
				.findViewById(R.id.main_title);

		View vTitle = inflater.inflate(R.layout.title_write_refresh, null);
		rlTitle.removeAllViews();
		rlTitle.addView(vTitle);

		// / 设置内容区
		LinearLayout llContent = (LinearLayout) ((Activity) context)
				.findViewById(R.id.llContent);
		View vContent = inflater.inflate(R.layout.weibo_list, null);
		llContent.removeAllViews();
		llContent.addView(vContent);

		/**
		 * 写微博键处理
		 */
		ImageButton ibWrite = (ImageButton) ((Activity) context).findViewById(R.id.IMAGE_BUTTON_WRITE);
		ibWrite.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(CreativeHallHandler.context,
						CreativeDesignActivity.class);
				((Activity) CreativeHallHandler.context).startActivity(intent);
			}
		});

		/**
		 * 刷新微博键处理
		 */
		ImageButton ibRefresh = (ImageButton) ((Activity) context).findViewById(R.id.IMAGE_BUTTON_REFRESH);
		ibRefresh.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (HallActivity.getCheckedId() != R.id.radio_hall) {
					return;
				}
				
		        if (weiboList != null) {
		        	weiboList.refreshNewWeiboList();
				}
			}
		});
		
        TextView tvTitle = (TextView) ((Activity) context).findViewById(R.id.TEXT_VIEW_TITLE);
        if (HallActivity.getUser() != null) {
        	tvTitle.setText(HallActivity.getUser().getScreenName());
        }

		/// 加载微博列表
        if (weiboList == null) {
        	weiboList = new WeiboList(context, llContent);
		}
    	weiboList.showWeiboList();
    }
    
    void refreshShowProgressBar(boolean isShow) {
		if (HallActivity.getCheckedId() != R.id.radio_hall) {
			return;
		}
		
		ImageButton ibRefresh = (ImageButton) ((Activity) context)
				.findViewById(R.id.IMAGE_BUTTON_REFRESH);
		ProgressBar pbRefresh = (ProgressBar) ((Activity) context)
				.findViewById(R.id.PROGRESS_BAR_WAITING);
		if (isShow) {
			ibRefresh.setVisibility(View.GONE);
			pbRefresh.setVisibility(View.VISIBLE);
		} else {
			ibRefresh.setVisibility(View.VISIBLE);
			pbRefresh.setVisibility(View.GONE);
		}
    }

	/**
	 * 内部类，实现微博数据获取
	 * @author wation.haliyoo
	 *
	 */
	class WeiboList extends WeiboLayout{
		@Override
		public List<WeiboBean> onGetNewWeiboList() {
			// TODO Auto-generated method stub
			if (HallActivity.getCheckedId() != R.id.radio_hall) {
				return null;
			}
			
			if (LoginActivity.getUser() == null) {
				Toast.makeText(context, 
						R.string.STR_NONE_USER, 
						Toast.LENGTH_SHORT).show();
			} else {
				List<WeiboBean> wbList = new ArrayList<WeiboBean>();

				try {
					Weibo weibo = OAuthConstant.getInstance().getWeibo();
					
					weibo.setToken(OAuthConstant.getInstance().getToken(), 
							OAuthConstant.getInstance().getTokenSecret());
					
					List<Status> weiboList = null;

					weiboList = getWeiboList(weibo, new Paging(getMaxReadWeiboId()));
					
					/// 清空原有list所有项
					//wbList.clear();
					
					if (weiboList == null) {
						return null;
					}
					
					for (Status status : weiboList) {
						WeiboBean wb = getWeiboByStatus(status, weibo);
						
						if (wb == null) {
							return null;
						}
						
						wbList.add(wb);
					}
					
					return wbList;
				} catch (WeiboException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			return null;
		}

		@Override
		public List<WeiboBean> onGetOldWeiboList() {
			// TODO Auto-generated method stub
			if (HallActivity.getCheckedId() != R.id.radio_hall) {
				return null;
			}
			
			if (LoginActivity.getUser() == null) {
				Toast.makeText(context, 
						R.string.STR_NONE_USER, 
						Toast.LENGTH_SHORT).show();
			} else {
				List<WeiboBean> wbList = new ArrayList<WeiboBean>();

				try {
					Weibo weibo = OAuthConstant.getInstance().getWeibo();
					
					weibo.setToken(OAuthConstant.getInstance().getToken(), 
							OAuthConstant.getInstance().getTokenSecret());
					
					List<Status> weiboList = null;

					/// 从最老的微博开始往前再获取20条微博
					weiboList = getWeiboList(weibo, new Paging(1, 20, 1, getMinReadWeiboId() - 1));
					
					/// 清空原有list所有项
					//wbList.clear();
					
					if (weiboList == null) {
						return null;
					}
					
					for (Status status : weiboList) {
						WeiboBean wb = getWeiboByStatus(status, weibo);
						
						if (wb == null) {
							return null;
						}
						
						wbList.add(wb);
					}
					
					return wbList;
				} catch (WeiboException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			return null;
		}
		
		WeiboBean getWeiboByStatus(Status status, Weibo weibo) throws WeiboException {
			WeiboBean wb = new WeiboBean();
			
			/// 标识
			wb.setWeiboId(status.getId());
			
			/// 头像
			//wb.setProfile(BitmapGet.getHttpBitmap(status.getUser().getProfileImageURL()));
			wb.setProfileUrl(status.getUser().getProfileImageURL().toString());
			
			/// 用户名
			wb.setUser(status.getUser().getScreenName());
			
			/// 微博
			wb.setText(status.getText());
			
			/// 时间
			wb.setTime(status.getCreatedAt());
			
			/// 是否包含图片
			if (status.getThumbnail_pic() == null || status.getThumbnail_pic().equals("")){
				wb.setExistImage(false);
			} else {
				wb.setIconUrl(status.getOriginal_pic());
				wb.setExistImage(true);
			}
			
			/// 是否包含定位信息
			if (status.getLatitude() > 0.0 && status.getLongitude() > 0.0) {
				wb.setExistLocation(true);
				wb.setLatitude(status.getLatitude());
				wb.setLongitude(status.getLongitude());
			} else {
				wb.setExistLocation(false);
			}
			
			/// 是否为转发的
			if (status.isRetweet()) {
				WeiboBean retweet = new WeiboBean();
				Status retweetStatus = status.getRetweeted_status();
				
				retweet.setUser(retweetStatus.getUser().getScreenName());
				retweet.setText(retweetStatus.getText());
				
				/// 是否包含图片
				if (retweetStatus.getThumbnail_pic() == null || retweetStatus.getThumbnail_pic().equals("")){
					retweet.setExistImage(false);
				} else {
					retweet.setIconUrl(retweetStatus.getOriginal_pic());
					retweet.setExistImage(true);
				}
				
				/// 获取转发原微博的转发数和评论数
				List<Count> counts = weibo.getCounts(new Long(retweetStatus.getId()).toString());

				if (counts != null && counts.size() > 0) {
					Count count = counts.get(0);
					
					Log.i(TAG, "count: " + count.toString());
					
					retweet.setRepostCount((int) count.getRt());
					retweet.setCommentCount((int) count.getComments());
				} else {
					retweet.setRepostCount(0);
					retweet.setCommentCount(0);
				}
				
				wb.setRetweet(retweet);
				
			}

			/// 获取转发原微博的转发数和评论数
			List<Count> counts = weibo.getCounts(new Long(status.getId()).toString());
			
			if (counts != null && counts.size() > 0) {
				Count count = counts.get(0);
				
				Log.i(TAG, "count: " + count.toString());
				
				wb.setRepostCount((int) count.getRt());
				wb.setCommentCount((int) count.getComments());
			} else {
				wb.setRepostCount(0);
				wb.setCommentCount(0);
			}
			
			/// 获取来源
			String source = status.getSource();
			if (source.length() > 0) {
				wb.setComeString(AdUserConstant.getSourceByXml(source));
			}
			
			return wb;
		}
		
		private List<Status> getWeiboList(Weibo weibo, Paging paging) {
			// TODO Auto-generated method stub
			if (HallActivity.getCheckedId() != R.id.radio_hall) {
				return null;
			}

			try {
				if (weibo == null) {
					return null;
				}
				return weibo.getFriendsTimeline(paging);
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		WeiboList(Context context, LinearLayout llContent) {
			super(context, llContent);
			// TODO Auto-generated constructor stub
			if (HallActivity.getCheckedId() != R.id.radio_hall) {
				return;
			}
		}

		@Override
		public void onShowWeiboDetail(AdapterView<?> arg0, View view, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			if (HallActivity.getCheckedId() != R.id.radio_hall) {
				return;
			}
			
			Object obj = view.getTag();
			if (obj != null) {
				long id = (Long) obj;
				Intent intent = new Intent(context,
						CreativeActivity.class);
				Bundle b = new Bundle();
				b.putLong("key", id);
				intent.putExtras(b);
				context.startActivity(intent);
			}
		}

		@Override
		public void onStartRefresh() {
			// TODO Auto-generated method stub
			if (HallActivity.getCheckedId() != R.id.radio_hall) {
				return;
			}

        	refreshShowProgressBar(true);
		}

		@Override
		public void onStopRefresh() {
			// TODO Auto-generated method stub
			if (HallActivity.getCheckedId() != R.id.radio_hall) {
				return;
			}

        	refreshShowProgressBar(false);
		}
	}

	public static User getUser() {
		// TODO Auto-generated method stub
		return user;
	}
}
